<?php


namespace app\admin\model;


use app\common\lib\RespCode;
use app\common\model\BaseModel;
use custom\Err;

class MessageAgentHouse extends BaseModel {

    /**
     * 列表
     * @param $params
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function getList($params) {
        $map = [];
        if (!empty($params['name'])) {
            $map[] = ['ca.name', 'like', '%' . trim($params['name']) . '%'];
        }
        if (!empty($params['start_time']) && !empty($params['end_time'])) {
            $map[] = ['mah.itime', 'between', [strtotime($params['start_time']), strtotime($params['end_time'])+86399]];
        }
        $count = self::alias('mah')
            ->leftJoin('company_agent ca', 'ca.id = mah.agent_id')
            ->where($map)
            ->count();
        if (empty($count)) {
            $result = [
                'page'    => 1,
                'pageNum' => 1,
                'count'   => 0,
                'data'    => [],
            ];
        } else {
            $page = empty($params['page']) ? 1 : intval($params['page']);
            $long = empty($params['long']) ? 10 : intval($params['long']);
            $data = self::alias('mah')
                ->leftJoin('company_agent ca', 'ca.id = mah.agent_id')
                ->page($page, $long)
                ->order('mah.id', 'desc')
                ->field('ca.name,mah.title,mah.id,mah.itime')
                ->where($map)
                ->select()
                ->toArray();
            foreach ($data as $k => $v) {
                $data[$k]['itime'] = date('Y-m-d H:i:s',$data[$k]['itime']);
            }
            $pageNum = ceil($count / $long);
            $result = [
                'page'    => $page,
                'pageNum' => $pageNum,
                'count'   => $count,
                'data'    => $data,
            ];
        }
        return $result;
    }

    /**
     * 删除
     * @param $params
     * @return bool
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public static function del($params) {
        if (!self::where('id', $params['id'])->select()->toArray()) {
            Err::add('数据不存在', RespCode::PARAMS_ERR);
            return false;
        }
        self::where('id', $params['id'])->delete();
        return true;
    }

}
